package com.open.capacity.form.controller;


import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.form.model.FormDbLink;
import com.open.capacity.form.model.FormDbTable;
import com.open.capacity.form.service.FormDbLinkService;
import com.open.capacity.form.service.FormDbTableService;
import com.open.capacity.form.vo.FormDbTableFieldVo;
import com.open.capacity.form.vo.FormDbTableVo;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.list.TreeList;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 数据表管理
 */
@RestController
@Api(tags = "数据表模块api")
public class FormDbTableController {


    @Autowired
    private FormDbLinkService dbLinkService;

    @Autowired
    private FormDbTableService dbTableService;


    /**
     * 查询数据表
     *
     * @param dbKey 数据库配置key
     * @return
     */
    @PreAuthorize("hasAuthority('dbTable:get/dbTables')")
    @ApiOperation(value = "查询数据表list")
    @GetMapping("/dbTables")
    @LogAnnotation(name = "表单", module = "form-center", recordRequestParam = false)
    public Result findDbTables(@RequestParam(value = "dbKey") String dbKey, @RequestParam(value = "tableName", required = false, defaultValue = "") String tableName) {
        List<FormDbTableVo> list = dbTableService.findList(dbKey, tableName);
        return Result.succeed(list);
    }


    /**
     * 查询数据表tree
     *
     * @return
     */
    @PreAuthorize("hasAuthority('dbLink:get/dbTables')")
    @ApiOperation(value = "查询数据库表tree")
    @GetMapping("/dbTables/tree")
    @LogAnnotation(name = "表单", module = "form-center", recordRequestParam = false)
    public Result<List<TreeVo>> treeDbTables(String parentId) {
        Map<String, Object> params = new HashMap<>();
        List<FormDbLink> dbLinks = dbLinkService.findDbLinks(params);
        List<TreeVo> treeList = new TreeList();
        if (StringUtils.isNotEmpty(parentId)) {
            List<FormDbTableVo> tables = dbTableService.findList(parentId, "");
            for (FormDbTableVo table : tables) {
                TreeVo child = new TreeVo();
                child.setId(table.getTableName());
                child.setText(table.getTableName());
                child.setValue(parentId);
                child.setShowcheck(false);
                child.setCheckstate(0);
                child.setIsexpand(false);
                child.setComplete(false);
                child.setParentId(parentId);
                child.setHasChildren(false);
                treeList.add(child);
            }
        } else {
            dbLinks.forEach(m -> {
                TreeVo node = new TreeVo();
                node.setId(m.getId());
                node.setText(m.getDbName());
                node.setValue(m.getId());
                node.setShowcheck(false);
                node.setCheckstate(0);
                node.setIsexpand(false);
                node.setComplete(false);
                node.setParentId("0");
                node.setHasChildren(true);
                treeList.add(node);
            });
        }


        return Result.succeed(treeList);
    }

    /**
     * 获取表字段集合信息
     *
     * @param dbKey     数据库配置key
     * @param tableName 表名
     * @return
     */
    @ApiOperation(value = "获取表字段集合信息")
    @PreAuthorize("hasAuthority('dbTable:get/dbTables/listFields')")
    @GetMapping("/dbTables/listFields")
    public Result<List<FormDbTableFieldVo>> listFieldsByTableName(@RequestParam(value = "dbKey") String dbKey, @RequestParam(value = "tableName", required = false) String tableName) {
        List<FormDbTableFieldVo> list = dbTableService.findFieldsByTableName(dbKey, tableName);
        return Result.succeed(list);
    }


    /**
     * 根据数据库执行sql语句,查询数据->datatable
     *
     * @param dbKey 数据库配置key
     * @return
     */
    @PreAuthorize("hasAuthority('dbTable:get/dbTables/getTableData')")
    @ApiOperation(value = "查询表数据数据")
    @GetMapping("/dbTables/getTableData")
    @LogAnnotation(name = "表单", module = "user-center", recordRequestParam = false)
    public Result getTableData(@RequestParam(value = "dbKey") String dbKey, @RequestParam(name = "tableName") String tableName, @RequestParam(name = "field") String field, @RequestParam(name = "logic") String logic, @RequestParam(name = "keyword") String keyword, @RequestParam(name = "params", required = false) Map<String, Object> params) {
        String sql = "select * from " + tableName;
        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(logic) && StringUtils.isNotEmpty(keyword)) {
            sql += " where " + field + logic + keyword;
        }
        List<Map<String, Object>> list = dbTableService.findData(dbKey, sql, new HashMap<>());
        return Result.succeed(list);
    }

    /**
     * 获取表字段集合信息
     *
     * @param dbKey     数据库配置key
     * @param tableName 表名
     * @return
     */
    @ApiOperation(value = "获取表字段集合信息")
    @PreAuthorize("hasAuthority('dbTable:get/dbTables/listFields')")
    @GetMapping("/dbTables/treeFields")
    public Result<List<TreeVo>> treeFieldsByTableName(@RequestParam(value = "dbKey") String dbKey, @RequestParam(value = "tableName", required = false) String tableName) {
        List<FormDbTableFieldVo> list = dbTableService.findFieldsByTableName(dbKey, tableName);

        List<TreeVo> treeList = new TreeList();
        list.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getColumnName());
            node.setText(m.getColumnName());
            node.setTitle(m.getColumnComment());
            node.setValue(m.getColumnName());
            node.setShowcheck(true);
            node.setCheckstate(0);
            node.setIsexpand(false);
            node.setComplete(false);
            node.setParentId("0");
            node.setHasChildren(false);

            treeList.add(node);
        });

        return Result.succeed(treeList);
    }

    /**
     * 根据数据库执行sql语句,查询数据->datatable
     *
     * @param dbKey 数据库配置key
     * @return
     */
    @PreAuthorize("hasAuthority('dbTable:get/dbTables/findData')")
    @ApiOperation(value = "查询表数据数据")
    @GetMapping("/dbTables/findData")
    @LogAnnotation(name = "表单", module = "user-center", recordRequestParam = false)
    public Result findData(@RequestParam(value = "dbKey") String dbKey, @RequestParam(name = "sql") String sql, @RequestParam(name = "params", required = false) Map<String, Object> params) {
        List<Map<String, Object>> list = dbTableService.findData(dbKey, sql, params);
        return Result.succeed(list);
    }


    /**
     * 根据数据库执行sql语句
     *
     * @param dbKey 数据库配置key
     * @return
     */
    @PreAuthorize("hasAuthority('dbTable:get/dbTables/{dbKey}/excuteSql')")
    @ApiOperation(value = "根据数据库执行sql语句")
    @GetMapping("/dbTables/{dbKey}/excuteSql")
    @LogAnnotation(name = "表单", module = "form-center", recordRequestParam = false)
    public Result excuteSql(@PathVariable(value = "dbKey") String dbKey, @RequestParam(name = "sql") String sql, @RequestParam(name = "params", required = false) Map<String, Object> params) {
        Integer result = dbTableService.excuteSqlWithParams(dbKey, sql, params);
        return Result.succeed(result);
    }

    /**
     * 数据表新增或者更新
     *
     * @param dbTable
     * @param keyValue
     * @return
     */
    @PreAuthorize("hasAnyAuthority('dbTable:post/dbTables','dbField:put/dbTables')")
    @ApiOperation(value = "数据表新增或者更新")
    @PostMapping("/dbTables/saveOrUpdate")
    @LogAnnotation(name = "表单", module = "form-center", recordRequestParam = false)
    public Result saveOrUpdate(@RequestBody FormDbTable dbTable, String keyValue) {

        return Result.succeed("发布成功");
    }
}
